<template>
  <div class="FacilityAdmin">
    <a-card>
      <a-form :form="form">
        <a-row :gutter="30">
          <a-col :span="8">
            <a-form-item label="设备编号" :label-col="{ span: 6}" :wrapper-col="{ span: 16, offset: 1}">
              <a-input placeholder="请输入" v-decorator="['facilityNumber']" />
            </a-form-item>
          </a-col>
          <a-col :span="8">
            <a-form-item
              label="代理商名称"
              :label-col="{ span: 6}"
              :wrapper-col="{ span: 16, offset: 1}"
            >
              <a-input placeholder="请输入姓名/昵称" v-decorator="['agentName']" />
            </a-form-item>
          </a-col>
          <a-col :span="8">
            <a-form-item label="配置状态" :label-col="{ span: 6 }" :wrapper-col="{ span: 16,offset:1 }">
              <a-select style="width:100%" v-decorator="['configure']" placeholder="全部">
                <a-select-option value>全部</a-select-option>
                <a-select-option
                  v-for="item in configAgentSelect"
                  :key="item.id"
                  :value="item.id"
                >{{item.name}}</a-select-option>
              </a-select>
            </a-form-item>
          </a-col>
        </a-row>
        <a-row :gutter="30">
          <a-col :span="8">
            <a-form-item label="设备状态" :label-col="{ span: 6 }" :wrapper-col="{ span: 16,offset:1 }">
              <a-select style="width:100%" v-decorator="['facilityStatus']" placeholder="全部">
                <a-select-option value>全部</a-select-option>
                <a-select-option
                  v-for="item in onlineSelect"
                  :key="item.id"
                  :value="item.id"
                >{{item.name}}</a-select-option>
              </a-select>
            </a-form-item>
          </a-col>
          <a-col :span="8">
            <a-form-item label="激活状态" :label-col="{ span: 6 }" :wrapper-col="{ span: 16,offset:1 }">
              <a-select style="width:100%" v-decorator="['activationStatus']" placeholder="全部">
                <a-select-option value>全部</a-select-option>
                <a-select-option
                  v-for="item in activateSelect"
                  :key="item.id"
                  :value="item.id"
                >{{item.name}}</a-select-option>
              </a-select>
            </a-form-item>
          </a-col>
          <a-col :span="8">
            <a-form-item label="添加时间" :label-col="{ span: 6 }" :wrapper-col="{ span: 16,offset:1 }">
              <a-range-picker
                style="width: 100%"
                v-decorator="['rangeConfig']"
                show-time
                format="YYYY-MM-DD HH:mm:ss"
              />
            </a-form-item>
          </a-col>
        </a-row>
        <a-row :gutter="30">
          <a-col :span="24" :style="{ textAlign: 'right' }">
            <a-button type="primary" @click="getfindPage($event)">查询</a-button>
            <a-button type="dashed" style="margin: 0 15px" @click="listExport">导出</a-button>
            <a-button @click="handleReset()">重置</a-button>
          </a-col>
        </a-row>
      </a-form>
    </a-card>
    <a-card style="margin-top:2%">
      <a-button type="primary" icon="plus" @click="showModal">添加</a-button>
      <a-modal
        title="添加设备"
        :visible="visible"
        @ok="handleOk"
        @cancel="handleCancel"
        v-model="visible"
      >
        <template slot="footer">
          <a-button key="back" @click="handleCancel">取消</a-button>
          <a-button key="submit" type="primary" @click="handleOk">确定</a-button>
        </template>
        <a-form :form="form">
          <a-form-item label="设备编号" :label-col="{ span: 5 }" :wrapper-col="{ span: 12 }">
            <a-input placeholder="请输入" v-decorator="['facilityNumberAdd']" />
          </a-form-item>
          <a-form-item label="绑定代理商" :label-col="{ span: 5 }" :wrapper-col="{ span: 12 }">
            <a-select style="width:100%" v-decorator="['boundAgentAdd']" placeholder="请选择">
              <a-select-option
                v-for="item in agentSelect"
                :key="item.id"
                :value="item.name"
              >{{item.name}}</a-select-option>
            </a-select>
          </a-form-item>
        </a-form>
      </a-modal>
      <a-table
        style="margin-top:2%"
        class="table"
        :columns="columns"
        :dataSource="data"
        @change="handleTableChange"
        :rowKey="record => record.devId"
        :pagination="pagination"
      >
        <template slot="configurationStatus" slot-scope="text,record">
          <span>{{record.isConfigAgent==0?'未配置':'已配置'}}</span>
        </template>
        <template slot="activationStatus" slot-scope="text,record">
          <span>{{record.isActive==0?'待激活':'已激活'}}</span>
        </template>
        <template slot="operate" slot-scope="text,record">
          <span class="blue" @click="showAgent(text)">{{record.isConfigAgent==0?'配置代理商':''}}</span>
          <span
            class="blue"
            @click="showActivateConfirm(text)"
          >{{record.isActive==0&&record.isConfigAgent==1?'激活':''}}</span>
          <span
            class="red"
            @click="showback(text,record)"
          >{{record.isActive==0&&record.isConfigAgent==1?'回厂':''}}</span>
          <span
            class="blue"
            @click="showConfirm(text)"
            v-show="record.isConfigAgent==0?false:true"
          >{{record.isActive==0&&record.isConfigAgent==1?'':'锁定'}}</span>
          <span class="blue" @click="getDeviceWxCode(text,record)">下载货柜码</span>
        </template>
      </a-table>
    </a-card>
    <a-modal
      title="配置代理商"
      :visible="visibleAgent"
      @ok="handleAgentOk"
      @cancel="handleAgentCancel"
      v-model="visibleAgent"
    >
      <template slot="footer">
        <a-button key="back" @click="handleAgentCancel">取消</a-button>
        <a-button key="submit" type="primary" @click="handleAgentOk">确定</a-button>
      </template>
      <a-form :form="form">
        <a-form-item label="设备编号" :label-col="{ span: 5 }" :wrapper-col="{ span: 12 }">
          <a-input placeholder="请输入" v-decorator="['facilityNumberEdit']" />
        </a-form-item>
        <a-form-item label="绑定代理商" :label-col="{ span: 5 }" :wrapper-col="{ span: 12 }">
          <a-select style="width:100%" v-decorator="['boundAgentEdit']" placeholder="请选择">
            <a-select-option
              v-for="item in agentEditSelect"
              :key="item.id"
              :value="item.name"
            >{{item.name}}</a-select-option>
          </a-select>
        </a-form-item>
      </a-form>
    </a-modal>
  </div>
</template>

<script>
const columns = [
  {
    title: "设备编号",
    dataIndex: "devCode",
    key: "facilityNumber",
    scopedSlots: { customRender: "facilityNumber" },
    align: "center"
  },
  {
    title: "配置状态",
    dataIndex: "isConfigAgent",
    key: "configurationStatus",
    scopedSlots: { customRender: "configurationStatus" },
    align: "center"
  },
  {
    title: "所属代理商",
    dataIndex: "agentName",
    key: "agentName",
    scopedSlots: { customRender: "agentName" },
    align: "center"
  },
  {
    title: "激活状态",
    key: "activationStatus",
    scopedSlots: { customRender: "activationStatus" },
    dataIndex: "isActive",
    align: "center"
  },
  {
    title: "设备状态",
    key: "facilityStatus",
    dataIndex: "isOnline",
    scopedSlots: { customRender: "facilityStatus" },
    align: "center"
  },
  {
    title: "添加时间",
    dataIndex: "createTime",
    key: "addTime",
    scopedSlots: { customRender: "addTime" },
    align: "center"
  },
  {
    title: "操作",
    dataIndex: "",
    scopedSlots: { customRender: "operate" },
    key: "operate",
    align: "center"
  }
];
export default {
  name: "FacilityAdmin",
  data() {
    return {
      dateFormat: "YYYY/MM/DD",
      monthFormat: "YYYY/MM",
      form: this.$form.createForm(this),
      data: [],
      agentSelect: [],
      agentEditSelect: [],
      activateSelect: [], //激活状态选择框数据
      configAgentSelect: [],
      onlineSelect: [],
      columns,
      visible: false,
      visibleAgent: false,
      AgentLoading: false,
      pagination: {
        showSizeChanger: true,
        showQuickJumper: true,
        pageSizeOptions: ["10", "20", "30", "40"], //每页条数选择器
        showTotal: (total, range) => {
          return `${range[0]}-${range[1]} 共${total}条`;
        }, // 总数展示
        pageSize: 10, //每页条数
        defaultCurrent: 1, //默认当前页
        current: 1, //当前页
        total: 50 //数据总条数
      }
    };
  },
  methods: {
    handleReset() {
      this.form.resetFields();
      this.startTime = "";
      this.endTime = "";
    },
    showModal() {
      this.visible = true;
      this.addInit();
    },
    handleOk(e) {
      var values = this.form.getFieldsValue();
      if (!values.facilityNumberAdd) {
        this.$message.warning("设备编号不能为空");
      } else if (!values.boundAgentAdd) {
        this.$message.warning("绑定代理商不能为空");
      } else {
        this.visible = false;
        this.save();
      }
    },
    handleCancel(e) {
      this.visible = false;
    },
    showAgent(text) {
      this.visibleAgent = true;
      this.devId = text.devId;
      this.deviceAgentId = text.deviceAgentId;
      this.editInit(text);
    },
    handleAgentOk(e) {
      this.AgentLoading = true;
      this.edit(this.devId, this.deviceAgentId);
      this.visibleAgent = false;
      this.AgentLoading = false;
    },
    handleAgentCancel(e) {
      this.visibleAgent = false;
    },

    showActivateConfirm(text) {
      var that = this;
      this.text = text;
      this.$confirm({
        title: "确认激活",
        content: "确认要激活该设备吗？",
        okText: "确定",
        cancelText: "取消",
        iconType: "info-circle",
        onOk() {
          that.active(that.text);
        },
        onCancel() {}
      });
    },

    showback(text, record) {
      var that = this;
      this.backId = text.devId;
      this.$confirm({
        title: "确认回厂该设备吗？",
        content: "回厂后这个设备才能重新绑定代理商,需要再次激活.",
        okText: "确定",
        cancelText: "取消",
        iconType: "info-circle",
        onOk() {
          that.back();
        },
        onCancel() {}
      });
    },

    showConfirm(text) {
      var that = this;
      this.text = text;
      this.$confirm({
        title: "确认对该设备锁定吗？",
        content: "锁定后这台设备将不能正常使用，需要再次激活之后才能使用。",
        okText: "确定",
        cancelText: "取消",
        iconType: "info-circle",
        onOk() {
          that.lock(that.text);
        },
        onCancel() {}
      });
    },
    handleTableChange(pagination, filters, sorter) {
      const pager = { ...this.pagination };
      pager.current = pagination.current;
      pager.pageSize = pagination.pageSize;
      pager.total = pagination.total;
      this.pagination = pager;

      this.getfindPage();
    },
    // 列表初始化
    listInit() {
      this.axios
        .post(this.baseUrl + "/device/listInit", {
          loginToken: this.$store.state.loginToken
        })
        .then(response => {
          // console.log(response);
          this.activateSelect = response.data.data.active;
          this.configAgentSelect = response.data.data.configAgent;
          this.onlineSelect = response.data.data.online;
        });
    },
    // 展示查询数据
    getfindPage($event) {
      if ($event) {
        this.pagination.current = 1;
      }
      var values = this.form.getFieldsValue();
      if (values.rangeConfig == undefined) {
        values.rangeConfig == undefined;
      } else {
        this.startTime = this.$moment(values.rangeConfig[0]._d).format(
          "YYYY-MM-DD HH:mm:ss"
        );
        this.endTime = this.$moment(values.rangeConfig[1]._d).format(
          "YYYY-MM-DD HH:mm:ss"
        );
      }
      this.axios
        .post(this.baseUrl + "/device/findPageListByCondition", {
          pageNum: this.pagination.current,
          pageSize: this.pagination.pageSize,
          active: values.activationStatus,
          agentName: values.agentName,
          configAgent: values.configure,
          devCode: values.facilityNumber,
          online: values.facilityStatus,
          loginToken: this.$store.state.loginToken,
          startTime: this.startTime,
          endTime: this.endTime
        })
        .then(response => {
          console.log(response);
          this.data = response.data.data.list;
          this.pagination.total = response.data.data.total;
          this.pagination.pageSize = response.data.data.pageSize;
          this.pagination.current = response.data.data.pageNum;
        });
    },
    // 新增设备初始化
    addInit() {
      this.axios
        .post(this.baseUrl + "/device/addInit", {
          loginToken: this.$store.state.loginToken
        })
        .then(response => {
          console.log(response);
          this.agentSelect = response.data.data;
        });
    },
    formatter(text, list) {
      if (Number(text)) {
        for (let i = 0; i < list.length; i++) {
          if (text == list[i].id) {
            return list[i].name;
          }
        }
      } else {
        for (let i = 0; i < list.length; i++) {
          if (text == list[i].name) {
            return list[i].id;
          }
        }
      }
    },
    // 新增设备
    save() {
      var values = this.form.getFieldsValue();
      this.axios
        .post(this.baseUrl + "/device/save", {
          loginToken: this.$store.state.loginToken,
          agentId: this.formatter(values.boundAgentAdd, this.agentSelect),
          devCode: values.facilityNumberAdd
        })
        .then(response => {
          if (response.data.code == 0) {
            this.$message.info("新增成功");
            this.getfindPage();
          }
        });
    },
    // 编辑设备初始化
    editInit(text) {
      var values = this.form.getFieldsValue();
      this.axios
        .post(this.baseUrl + "/device/editInit", {
          loginToken: this.$store.state.loginToken,
          deviceAgentId: text.deviceAgentId,
          id: text.devId
        })
        .then(response => {
          console.log(response);
          this.agentEditSelect = response.data.data.agentLIst;
          this.agentId = response.data.data.agentId;
          this.form.setFieldsValue({
            facilityNumberEdit: text.devCode,
            boundAgentEdit: this.formatter(this.agentId, this.agentEditSelect)
          });
        });
    },
    // 编辑商品
    edit(id, deviceAgentId) {
      var values = this.form.getFieldsValue();
      // console.log(values);
      this.axios
        .post(this.baseUrl + "/device/edit", {
          loginToken: this.$store.state.loginToken,
          agentId: this.formatter(values.boundAgentEdit, this.agentEditSelect),
          devCode: values.facilityNumberEdit,
          devId: id,
          deviceAgentId: deviceAgentId
        })
        .then(response => {
          console.log(response);
          if (response.data.code == 0) {
            this.$message.info("编辑成功");
            this.getfindPage();
          }
        });
    },
    // 激活设备
    active(text) {
      var values = this.form.getFieldsValue();
      this.axios
        .post(this.baseUrl + "/device/active", {
          loginToken: this.$store.state.loginToken,
          id: text.devId,
          isActive: 1
        })
        .then(response => {
          console.log(response);
          if (response.data.code == 0) {
            this.$message.info("激活设备成功");
            this.getfindPage();
          }
        });
    },

    // 回厂
    back() {
      this.axios
        .post(this.baseUrl + "/device/back", {
          loginToken: this.$store.state.loginToken,
          id: this.backId
        })
        .then(response => {
          console.log(response);
          if (response.data.code == 0) {
            this.$message.info("设备回厂成功");
            this.getfindPage();
          }
        });
    },

    // 锁定设备
    lock(text) {
      this.axios
        .post(this.baseUrl + "/device/active", {
          loginToken: this.$store.state.loginToken,
          id: text.devId,
          isActive: 0
        })
        .then(response => {
          console.log(response);
          if (response.data.code == 0) {
            this.$message.info("锁定设备成功");
            this.getfindPage();
          }
        });
    },
    // 导出商品列表
    listExport() {
      var values = this.form.getFieldsValue();
      this.axios
        .post(
          this.baseUrl + "/device/export",
          {
            active: values.activationStatus,
            agentName: values.agentName,
            configAgent: values.configure,
            devCode: values.facilityNumber,
            online: values.facilityStatus,
            loginToken: this.$store.state.loginToken
          },
          { responseType: "arraybuffer" }
        )
        .then(response => {
          console.log(response);
          if (response.status == "200") {
            const aLink = document.createElement("a");
            let blob = new Blob([response.data], {
              type: "application/vnd.ms-excel"
            });
            aLink.href = URL.createObjectURL(blob);
            aLink.download = "设备管理表";
            aLink.click();
            document.body.appendChild(aLink);
          }
        });
    },

    // 获取设备微信识别码
    getDeviceWxCode(text, record) {
      this.axios
        .post(this.baseUrl + "/device/getDeviceWxCode", {
          loginToken: this.$store.state.loginToken,
          name: record.devCode,
          path: `pages/common/dispatcher/dispatcher?deviceId=${record.devCode}`
        })
        .then(response => {
          var alink = document.createElement("a");
          alink.href = response.data.data;
          alink.download = "微信二维码"; //图片名
          alink.click();
        });
    }
  },
  created() {
    this.listInit();
    this.getfindPage();
  }
};
</script>

<!-- Add "scoped" attribute to limit CSS to this component only -->
<style scoped>
.FacilityAdmin {
  width: 100%;
}
</style>
